from flask import Flask, request, jsonify
import net_usage as usage_model
import os
from werkzeug.utils import secure_filename

app = Flask("verify-code-recognize-app")

# 文件上传目录
app.config['UPLOAD_FOLDER'] = "static"+os.sep +"uploads"+os.sep
# 支持的文件格式
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg'}  # 集合类型

CODE_FAIL = -1
CODE_SUCCESS = 0

MSG_FAIL = "处理失败"
MSG_SUCCESS = "处理成功"


# 判断文件名是否是我们支持的格式
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/recognize/path', methods=['POST'])
def recognize_path():
    filePathList = request.json['filePathList']
    code = CODE_SUCCESS
    msg = MSG_SUCCESS
    data = []
    for filePath in filePathList:
        if not os.path.exists(filePath):
            # code = CODE_FAIL
            # msg = "文件不存在"
            print("文件不存在:", filePath)
            data.append("")
            continue
        else:
            labels = usage_model.usage(filePath)
            data.append(''.join(labels))
    result = {'code': code, "msg": msg, "data": data}
    return jsonify(result)


@app.route('/recognize/file', methods=['POST'])
def recognize_file():
    upload_file = request.files['image']
    code = CODE_SUCCESS
    msg = MSG_SUCCESS
    data = None

    if upload_file and allowed_file(upload_file.filename):
        filename = secure_filename(upload_file.filename)
        # 将文件保存到 static/uploads 目录，文件名同上传时使用的文件名
        dir = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'])
        if not os.path.exists(dir):
            os.makedirs(dir)

        filePath = os.path.join(dir, filename)
        print("upload filePath:", filePath)
        upload_file.save(filePath)
        data = ''.join(usage_model.usage(filePath))
    else:
        code = CODE_FAIL
        msg = "保存文件失败"

    result = {'code': code, "msg": msg, "data": data}
    return jsonify(result)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8066, debug=False)